<script setup>
import router from '@/router';
import { computed, ref, watch } from 'vue';
import { ElNotification } from 'element-plus'
import { useUserStore } from '@/MyStore/Store';

const UserStore = useUserStore();

// 判断id是否合法
// 拿到账号
let ID = ref('')
let isIdValid = computed(() => /^\d{11}$/.test(ID.value));
const showHint = ref(false); // 控制提示信息显示的状态
watch(ID, () => {
  showHint.value = !isIdValid.value;
});

// 判断密码是否合法
// 拿到密码
let PWD = ref('')
let isPwdValid = computed(() => /^[A-Za-z0-9]{8}$/.test(PWD.value));
const showHintpwd = ref(false); // 控制提示信息显示的状态
watch(PWD, () => {
  showHintpwd.value = !isPwdValid.value;
});


function onLoginSuccess() {
  // 使用 ElNotification.success 显示成功的提示信息
  ElNotification.success({
    title: '欢迎',
    message: '登录成功',
    offset: 100, // 通知位置偏移，避免被滚动条或导航栏遮挡
  });
}

function onLoginFail() {
  // 使用 ElNotification.error 显示错误提示信息
  ElNotification.error({
    title: '提示',
    message: '登录失败: 账号或密码错误', // 假设 error 对象包含 message 属性
    offset: 100, // 通知位置偏移
  });
}

//登陆功能
function submit() {

  //拿到输入框的数据
  let data = { id: ID.value, pwd: PWD.value }

  fetch("/api/Login", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data)
  })
    .then((response) => {
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      console.log(data)
      return response.json();
    })
    .then((resp) => {
      //登陆成功后将数据存入pinia，然后跳转至主页，主页nickname默认为ID
      if (resp.message == 'ok') {
        let loginUser = resp.data.info;
        UserStore.setUserInfo(ID.value, loginUser.userName, PWD.value)
        router.push("/Index");
        //登陆成功的提示
        onLoginSuccess();
      } else {
        onLoginFail();
      }

    })
    .catch(error => {
      console.error("发生错误:", error);
    });
}

function register(){
  router.push('/Register')
}

</script>

<template>

  <!-- <el-button plain @click="open"> 登陆成功 </el-button> -->


  <!--背景图片作为底板-->
  <div class="bg-image">
    <div class="container justify-content-center">
      <div class="row justify-content-center">
        <div class="col-7">
          <img src="/akspic3.jpg" alt="" class="img-fluid">
        </div>
        <div class="col-5 formbackcolor justify-content-center">
          <div class="top m-5 letter-spacing">
            <i class="bi bi-twitch" style="font-size: 1.65rem"></i>
            <h4>&nbsp;欢迎使用图书分享平台</h4>
          </div>
          <form class=" m-5">
            <div class="row mb-5">
              <label for="ID" class="col-sm-2 col-form-label"><i class="bi bi-person-video"
                  style="font-size: 1.2rem"></i>账号</label>
              <div class="col-sm-10">
                <input type="text" class="form-control" id="okID" v-model="ID" @blur="checkAccount">
              </div>
              <div class="nothing">
                <div v-if="showHint" class="hint top">账号必须是11位数字！</div>
              </div>
            </div>
            <div class="row mb-5">
              <label for="password" class="col-sm-2 col-form-label"><i class="bi bi-file-lock"
                  style="font-size: 1.2rem"></i>密码</label>
              <div class="col-sm-10">
                <input type="password" class="form-control" id="okpassword" v-model="PWD">
              </div>
              <div class="nothing">
                <div v-if="showHintpwd" class="hint top">密码必须是8位数字或字母的任意组合！</div>
              </div>
              <div class="forgetpwd ml-2">
                <!-- <div>忘记密码</div> -->
              </div>
            </div>

            <div class="d-grid gap-2">
              <button class="btn btn btn btn-outline-dark" type="button" id="okbutton" @click="submit"><i
                  class="bi bi-telegram"></i>&nbsp;&nbsp;登陆</button>
            </div>
            <div class="row m-4 justify-content-center">
              <div class="col">
                <div class="top zhuce" type="button" id="Zhuce" @click="register">没有账号？点击注册</div>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>


<style scoped>
.forgetpwd {
  display: flex;
  justify-content: right;
  cursor: pointer;
  /* 鼠标悬停时显示指针手势 */
  transition: background-color 0.3s, color 0.3s;
  /* 平滑过渡效果 */
}

.forgetpwd:hover {
  color: gray;
  /* 鼠标悬停时的文字颜色 */
  text-decoration: underline;
  /* 鼠标悬停时显示下划线 */
}

.hint {
  color: red;
  font-size: 12px;
  margin-top: 5px;
}

.nothing {
  min-height: 30px;
}

.bg-image {
  /* 设置背景图 */
  background-image: url('/whiteblackbg.jpg');
  /* 背景图覆盖整个元素 */
  background-size: cover;
  /* 背景图不重复 */
  background-repeat: no-repeat;
  /* 背景图固定，不随滚动条滚动 */
  background-attachment: fixed;
  /* 背景图居中显示 */
  background-position: center;
  /* 元素的高度 */
  height: 100vh;
  /* 使.bg-image成为一个Flex容器 */
  display: flex;
  /* 垂直居中所有子元素 */
  align-items: center;
  /* 水平居中所有子元素 */
  justify-content: center;
  /* 确保Flex容器的子元素在水平和垂直方向上都居中 */
  flex-direction: column;
}

.formbackcolor {
  background-color: aliceblue;
  /* 设置背景颜色为浅蓝色 */
  border-radius: 0px;
  /* 添加圆角，数值可以根据需要调整 */
  opacity: 0.9;
  /* 设置透明度，范围从0（完全透明）到1（完全不透明） */
  border-top-right-radius: 30px;
  border-bottom-right-radius: 30px;
  box-shadow: 5px 5px 10px 2px rgba(0, 0, 0, 0.4);

}

.top {
  margin-left: auto;
  margin-right: auto;
  display: flex;
  justify-content: center;
}



.letter-spacing {
  letter-spacing: 3px;
  /* 调整字体之间的间距 */
}


img.img-fluid {
  width: 100%;
  /* 或者设置为与登录表单相同的宽度 */
  height: 100%;
  /* 保持图片的宽高比 */
  opacity: 0.65;
  margin: 0;
  padding: 0;
  border-top-left-radius: 30px;
  border-bottom-left-radius: 30px;
  box-shadow: 5px 5px 10px 2px rgba(0, 0, 0, 0.3);
}

.zhuce {
  cursor: pointer;
  /* 鼠标悬停时显示指针手势 */
  transition: background-color 0.3s, color 0.3s;
  /* 平滑过渡效果 */
}

.zhuce:hover {
  color: gray;
  /* 鼠标悬停时的文字颜色 */
  text-decoration: underline;
  /* 鼠标悬停时显示下划线 */
}
</style>